#include<string>
#include <sstream>
#include<map>
class Solution {
public:
    std::string org = "";
    int len = 0;
    int index=0;

    std::string countOfAtoms(std::string formula) {
        org = formula;
        len = formula.length();
        std::stringstream ss;
        std::map<std::string,int>* m = cr();
        for (const auto &p: *m)
        {
            ss<<p.first;
            if (p.second>1)
            {
                ss<<p.second;
            }
        }
        return ss.str();
    }
    std::map<std::string,int> * cr()
    {
        std::map<std::string,int>* m = new std::map<std::string,int>;
        while (index < len&&org[index]!=')')
        {
            std::map<std::string,int> *a = new std::map<std::string,int>;
            std::string b ="";
            bool flag = false;
            if (org[index] == '(')
            {
                flag = true;
                index++;
                a = cr();
                index++;
            }else
            {
                flag = false;
                b=fins();
            }
            int num = finn();
            if (flag)
            {
                for (const auto &p : *a)
                {
                    if (m->find(p.first) == m->end())
                    {
                        m->insert(std::pair<std::string,int>(p.first,p.second*num));
                    }else
                    {
                        (*m)[p.first] +=p.second*num;
                    }
                }
            }else
            {
                if (m->find(b)==m->end())
                {
                    m->insert(std::pair<std::string,int>(b,num));
                }else
                {
                    (*m)[b]+=num;
                }
            }
            delete a;
        }
        return m;
    }
    int finn()
    {
      
        std::stringstream s ;
  if (org[index]>'9'||org[index]<'0')
  {
      return 1;
  }
        while (index<len)
        {
          
            if (org[index]<='9'&&org[index]>='0')
            {
                s<<org[index];
               
            }
            else
            {
                break;
            }
            index++;
        }
        
        return std::stoi(s.str());
    }
    std::string fins()
    {
       std:: stringstream ss;
        ss<<org[index++];
        while (index < len&&org[index]<='z'&&org[index]>='a')
        {
            ss<<org[index++];
        }
        
        return ss.str();
    }
};

